package untils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionUtils {
    static String url;
    static String username;
    static String password;
    static {
        InputStream inputStream = ConnectionUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        url = properties.getProperty("url"); // = "jdbc:mysql://localhost:3306/clazz59?serverTimezone=GMT%2B8&characeterEncoding=utf-8";
        username = properties.getProperty("username"); // = "root";
        password = properties.getProperty("password"); // = "123456";
        System.out.println(username);
    }

    public static Connection getConnection() throws Exception {
        // 注册驱动 → 方案1
        //DriverManager.registerDriver(new Driver());
        // 注册驱动 → 方案2 → 检查你有没有这个类的字节码文件
        //Class.forName("com.mysql.cj.jdbc.Driver");
        // 注册驱动 → 方案3 → 直接省略不写 → 会自动注册
        // 把这些值放到配置文件中
        System.out.println("准备connection");
        Connection connection = DriverManager.getConnection(url, username, password);
        System.out.println("完成connection");
        return connection;
    }

    public static void close(Connection connection) throws SQLException {
        if (connection != null) {
            connection.close();
        }
    }
}
